package cn.xuqiudong.rpc.registry;

import cn.xuqiudong.rpc.common.constants.ConfigKey;
import cn.xuqiudong.rpc.common.util.PropertiesUtils;
import cn.xuqiudong.rpc.extension.XqdExtensionFactory;
import org.apache.commons.lang3.StringUtils;
import cn.xuqiudong.rpc.cluster.exception.XqdCommonException;

/**
 * 描述: 获取当前项目中单例的 注册中心， 屏蔽一些通用代码
 * @author Vic.xu
 * @date 2022-02-24 17:33
 */
public class RegistrySingle {

    private static volatile Registry registry;

    private RegistrySingle(){}

    /**
     * 获得配置的注册中心工厂
     */
    private static RegistryFactory registryFactory = XqdExtensionFactory.defaultExtendFactory().getAdaptiveXqdExtension(RegistryFactory.class);

    /**
     * 获得一个注册中心
     * @return
     */
    public static Registry getRegistry(){
        if (registry == null) {
            synchronized (RegistrySingle.class) {
                if (registry == null) {
                    String registryAddress = PropertiesUtils.getString(ConfigKey.REGISTRY_ADDRESS_CONFIG);
                    if (StringUtils.isEmpty(registryAddress)) {
                        throw new XqdCommonException("Please configure the registry address ， configuration item is:" + ConfigKey.REGISTRY_ADDRESS_CONFIG);
                    }
                    registry = registryFactory.getRegistry(registryAddress);
                }
            }
        }
        return registry;
    }


}
